import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class studentAdd {
    public static void main(String[] args) throws SQLException {
        //建立数据源
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java104?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("666666");

        //创建链接
        Connection connection=dataSource.getConnection();
        System.out.println(connection);

        //构建sql语句
        Scanner scanner=new Scanner(System.in);
        System.out.println("输入学号");
        int id=scanner.nextInt();
        System.out.println("输入姓名");
        String name=scanner.next();
        String sql1="create table  IF NOT EXISTS student(id int, name varchar(40));";
        String sqlAdd="insert into student values(?,?)";
        PreparedStatement ps=connection.prepareStatement(sql1);
        ps.executeUpdate();
        ps=connection.prepareStatement(sqlAdd);
        ps.setInt(1,id);
        ps.setString(2,name);
        ps.executeUpdate();

        //释放资源
        ps.close();
        connection.close();
    }
}
